package org.example.cet.demos.typehandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

// 声明该类型处理器处理的 Java 类型为 double 数组
@MappedTypes(double[].class)
// 声明该类型处理器处理的 JDBC 类型（这里假设为 VARCHAR，因为要将数组转换为字符串存储，实际根据数据库类型调整）
@MappedJdbcTypes(JdbcType.VARCHAR)
public class DoubleArrayTypeHandler extends BaseTypeHandler<double[]> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 设置参数到 PreparedStatement 中
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, double[] parameter, JdbcType jdbcType) throws SQLException {
        try {
            String json = objectMapper.writeValueAsString(parameter);
            ps.setString(i, json);
        } catch (Exception e) {
            throw new SQLException("Failed to convert double[] to JSON", e);
        }
    }

    // 从 ResultSet 中获取数据并转换为 double 数组
    @Override
    public double[] getNullableResult(ResultSet rs, String columnName) throws SQLException {
        try {
            String json = rs.getString(columnName);
            return json != null ? objectMapper.readValue(json, double[].class) : null;
        } catch (Exception e) {
            throw new SQLException("Failed to convert JSON to double[]", e);
        }
    }

    // 从 ResultSet 中获取数据并转换为 double 数组（根据列索引）
    @Override
    public double[] getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        try {
            String json = rs.getString(columnIndex);
            return json != null ? objectMapper.readValue(json, double[].class) : null;
        } catch (Exception e) {
            throw new SQLException("Failed to convert JSON to double[]", e);
        }
    }

    // 从 CallableStatement 中获取数据并转换为 double 数组
    @Override
    public double[] getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        try {
            String json = cs.getString(columnIndex);
            return json != null ? objectMapper.readValue(json, double[].class) : null;
        } catch (Exception e) {
            throw new SQLException("Failed to convert JSON to double[]", e);
        }
    }
}